package com.ekuaitu.kuaitustaff.application;

import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.os.Handler;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.mapapi.SDKInitializer;
import com.ekuaitu.kuaitustaff.BuildConfig;
import com.ekuaitu.kuaitustaff.activity.CarNewMainMapActivity;
import com.ekuaitu.kuaitustaff.api.ApiStore;
import com.ekuaitu.kuaitustaff.api.DebugUrlConstant;
import com.ekuaitu.kuaitustaff.api.UrlConstant;
import com.ekuaitu.kuaitustaff.bean.ForegroundBean;
import com.ekuaitu.kuaitustaff.utils.FileLogUtils;
import com.ekuaitu.kuaitustaff.utils.ForegroundCallbacks;
import com.ekuaitu.kuaitustaff.utils.Logger;
import com.ekuaitu.kuaitustaff.utils.Md5Utils;
import com.ekuaitu.kuaitustaff.utils.SPKey;
import com.ekuaitu.kuaitustaff.utils.SPUtils;
import com.ekuaitu.kuaitustaff.utils.VerControlUtils;
import com.ekuaitu.kuaitustaff.utils.ble.ViseBluetooth;
import com.ekuaitu.kuaitustaff.utils.bos.UpdateFile;
import com.inuker.bluetooth.library.BluetoothContext;
import com.inuker.bluetooth.library.ClientManager;
import com.readystatesoftware.chuck.ChuckInterceptor;
import com.tencent.bugly.Bugly;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import org.greenrobot.eventbus.EventBus;

import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.os.Build.VERSION.SDK;


public class MyApplication extends Application {

    private Context mContext = this;
    private String userId;
    private String userName;
    private String token;
    private String appVersion;
    private String timestamp;
    private String sign;
    private String headerToken;
    private String areaCode, adCode;
    private VerControlUtils verControl;
    public static String imageUrl;
    public static String hotLine;
    public static MyApplication instance;
    public static String[] curPosition = new String[2];
    public static ChuckInterceptor chuckInterceptor;
    public static List<String> findCarVip;

    public static MyApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        Bugly.init(this, "94ba2ad832", true);
        // 在使用 SDK 各组间之前初始化 context 信息，传入 ApplicationContext
        SDKInitializer.initialize(this);
        //蓝牙初始化
        BluetoothContext.set(this);
        ViseBluetooth.getInstance().init(this);
        ClientManager.initClient(this);
        initData();
        FileLogUtils.init(this);
        initUmeng();
        initConfigMode();
        ZXingLibrary.initDisplayOpinion(this);
        registerLifeCycle();
        if (BuildConfig.DEBUG) {
            chuckInterceptor = new ChuckInterceptor(mContext);
        }

    }

    private void initConfigMode() {
        if (BuildConfig.DEBUG) {
            Logger.i(SPKey.URLMODE, SPUtils
                    .getInstance(mContext).getIntValue(SPKey.URLMODE) + "");
            switch (SPUtils
                    .getInstance(this).getIntValue(SPKey.URLMODE)) {
                case 1:
                    UrlConstant.Request.BASE_URL_PARSE = DebugUrlConstant.DevUrl.BASE_URL_PARSE;
                    UrlConstant.Request.BASE_URL_NEW = DebugUrlConstant.DevUrl.BASE_URL_NEW;
                    UrlConstant.Request.BASE_URL_CONFIG = DebugUrlConstant.DevUrl.BASE_CONFIG_URL;

                    UrlConstant.Request.WORKLIST = DebugUrlConstant.DevUrl.WORKLIST;
                    UrlConstant.Request.HOTLINE = DebugUrlConstant.DevUrl.HOTLINE;
                    UrlConstant.Request.SETTING = DebugUrlConstant.DevUrl.SETTING;
                    UrlConstant.Request.PARK_FEE = DebugUrlConstant.DevUrl.PARK_FEE;
                    UrlConstant.Request.CAR_BREAK = DebugUrlConstant.DevUrl.CAR_BREAK;

                    break;
                case 0://默认test
                case 2:
                    UrlConstant.Request.BASE_URL_PARSE = DebugUrlConstant.TestUrl.BASE_URL_PARSE;
                    UrlConstant.Request.BASE_URL_NEW = DebugUrlConstant.TestUrl.BASE_URL_NEW;
                    UrlConstant.Request.BASE_URL_CONFIG = DebugUrlConstant.TestUrl.BASE_CONFIG_URL;

                    UrlConstant.Request.WORKLIST = DebugUrlConstant.TestUrl.WORKLIST;
                    UrlConstant.Request.HOTLINE = DebugUrlConstant.TestUrl.HOTLINE;
                    UrlConstant.Request.SETTING = DebugUrlConstant.TestUrl.SETTING;
                    UrlConstant.Request.PARK_FEE = DebugUrlConstant.TestUrl.PARK_FEE;
                    UrlConstant.Request.CAR_BREAK = DebugUrlConstant.TestUrl.CAR_BREAK;


                    break;
                case 4:
                    UrlConstant.Request.BASE_URL_PARSE = DebugUrlConstant.Dev2Url.BASE_URL_PARSE;
                    UrlConstant.Request.BASE_URL_NEW = DebugUrlConstant.Dev2Url.BASE_URL_NEW;
                    UrlConstant.Request.BASE_URL_CONFIG = DebugUrlConstant.Dev2Url.BASE_CONFIG_URL;

                    UrlConstant.Request.WORKLIST = DebugUrlConstant.Dev2Url.WORKLIST;
                    UrlConstant.Request.HOTLINE = DebugUrlConstant.Dev2Url.HOTLINE;
                    UrlConstant.Request.SETTING = DebugUrlConstant.Dev2Url.SETTING;
                    UrlConstant.Request.PARK_FEE = DebugUrlConstant.Dev2Url.PARK_FEE;
                    UrlConstant.Request.CAR_BREAK = DebugUrlConstant.Dev2Url.CAR_BREAK;


                    break;
                case 5:
                    UrlConstant.Request.BASE_URL_PARSE = DebugUrlConstant.Dev2Url.BASE_URL_PARSE;
                    UrlConstant.Request.BASE_URL_NEW = DebugUrlConstant.Dev2Url.BASE_URL_NEW;
                    UrlConstant.Request.BASE_URL_CONFIG = DebugUrlConstant.Dev2Url.BASE_CONFIG_URL;

                    UrlConstant.Request.WORKLIST = DebugUrlConstant.Dev2Url.WORKLIST;
                    UrlConstant.Request.HOTLINE = DebugUrlConstant.Dev2Url.HOTLINE;
                    UrlConstant.Request.SETTING = DebugUrlConstant.Dev2Url.SETTING;
                    UrlConstant.Request.PARK_FEE = DebugUrlConstant.Dev2Url.PARK_FEE;
                    UrlConstant.Request.CAR_BREAK = DebugUrlConstant.Dev2Url.CAR_BREAK;

                    break;
            }

        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private void initData() {
        verControl = new VerControlUtils(this);
        appVersion = verControl.getVersionName();
        timestamp = new Date().getTime() + "";
        try {
            sign = Md5Utils.getMD5String(timestamp + "incar");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    private void initUmeng() {
        UMConfigure.init(mContext, UMConfigure.DEVICE_TYPE_PHONE, "fe9dc9d99834098d6e658a45f01099c3");
        PushAgent mPushAgent = PushAgent.getInstance(mContext);
      /*  mPushAgent.setDebugMode(true);*/
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                //onRegistered方法的参数registrationId即是device_token
                Logger.i("deviceToken", deviceToken + "");
                SPUtils.getInstance(mContext).putStringValue("deviceToken", deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
            }
        });

        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            @Override
            public Notification getNotification(Context context, UMessage uMessage) {
                Logger.d("ummessage", "接收到通知1" + uMessage.custom.toString() + "");
                return super.getNotification(context, uMessage);
            }

            @Override
            public void dealWithCustomMessage(Context context, UMessage uMessage) {
                new Handler(getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Logger.d("ummessage", "接收到消息" + uMessage.custom.toString() + "");
                        if (uMessage.custom.contains("日志")) {
                            Logger.i("我要开始上传日志了哈哈哈......");
                            UpdateFile.getInstance().uploadPicToBos(mContext);
                        }
                    }
                });
            }

            @Override
            public void dealWithNotificationMessage(Context context, UMessage uMessage) {
                Logger.d("ummessage", "接收到通知2" + uMessage.custom.toString() + "");
                super.dealWithNotificationMessage(context, uMessage);
            }
        };
        mPushAgent.setMessageHandler(messageHandler);

        //接收友盟通知，需点击通知，即可接收自定义参数
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void launchApp(Context context, UMessage uMessage) {
                super.launchApp(context, uMessage);
            }

            @Override
            public void dealWithCustomAction(Context context, UMessage uMessage) {
            }
        };
        mPushAgent.setNotificationClickHandler(notificationClickHandler);

        mPushAgent.setNoDisturbMode(0, 0, 0, 0);
        mPushAgent.setMuteDurationSeconds(1);
        mPushAgent.setDisplayNotificationNumber(3);
        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER); //声音
        mPushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SERVER);//呼吸灯
        mPushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SERVER);//振动
    }

    private void registerLifeCycle() {
        ForegroundCallbacks.get(this).addListener(new ForegroundCallbacks.Listener() {
            @Override
            public void onBecameForeground() {
                Log.d("foregroundcallbacks", "到前台了");
                EventBus.getDefault().post(new ForegroundBean());
            }

            @Override
            public void onBecameBackground() {
                Log.d("foregroundcallbacks", "到后台了");
            }
        });
    }

    //uid
    public String getUserId() {
        if (userId == null || userId.equals("")) {
            userId = SPUtils.getInstance(getApplicationContext()).getStringValue("userId");
        }
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
        SPUtils.getInstance(getApplicationContext()).putStringValue("userId", userId);
    }

    //token
    public String getToken() {
        if (token == null || token.equals("")) {
            token = SPUtils.getInstance(getApplicationContext()).getStringValue("token");
        }
        return token;
    }

    public void setToken(String token) {
        this.token = token;
        SPUtils.getInstance(getApplicationContext()).putStringValue("token", token);
    }

    //headerToken
    public String getHeaderToken() {
        if (headerToken == null || headerToken.equals("")) {
            headerToken = SPUtils.getInstance(mContext).getStringValue("headerToken");
        }
        return headerToken;
    }

    public void setHeaderToken(String headerToken) {
        this.headerToken = headerToken;
        SPUtils.getInstance(mContext).putStringValue("headerToken", headerToken);
    }

    //areaCode
    public String getAreaCode() {
        if (areaCode == null || areaCode.equals("")) {
            areaCode = SPUtils.getInstance(mContext).getStringValue(SPKey.AREA_CODE);
        }
        return areaCode;
    }

    public void setAreaCode(String areaCode) {
        this.areaCode = areaCode;
        SPUtils.getInstance(mContext).putStringValue(SPKey.AREA_CODE, areaCode);
    }

    //adCode
    public String getAdCode() {
        if (TextUtils.isEmpty(adCode)) {
            adCode = SPUtils.getInstance(mContext).getStringValue(SPKey.AD_CODE);
        }
        return adCode;
    }

    public void setAdCode(String adCode) {
        this.adCode = adCode;
        SPUtils.getInstance(getApplicationContext()).putStringValue(SPKey.AD_CODE, adCode);
    }

    //sign
    public String getSign() {
        return sign;
    }

    //timestamp
    public String getTimestamp() {
        timestamp = new Date().getTime() + "";
        try {
            sign = Md5Utils.getMD5String(timestamp + "incar1");//时间戳+incar+1(平台)
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return timestamp;
    }

    //userName
    public String getUserName() {
        if (userName == null) {
            userName = SPUtils.getInstance(mContext).getStringValue("userName");
        }
        return userName;
    }

    public void setuserName(String userName) {
        this.userName = userName;
        SPUtils.getInstance(getApplicationContext()).putStringValue("userName", userName);
    }

    //appVersion
    public String getAppVersion() {
        if (appVersion == null || appVersion.equals("")) {
            appVersion = verControl.getVersionName();
        }
        return appVersion;
    }

    //sdkVersion
    public String getSdkVersion() {
        return SDK;
    }

    //curPosition
    public void setCurPosition(String latitude, String longitude) {
        if (!"".equals(latitude) && latitude != null) {
            curPosition[0] = latitude;
            curPosition[1] = longitude;
            SPUtils.getInstance(getApplicationContext()).putStringValue(SPKey.CUR_POSITION, latitude + "," + longitude);
        }
    }

    public String[] getCurPosition() {
        String savedCurPosition = SPUtils.getInstance(mContext).getStringValue(SPKey.CUR_POSITION);
        if (savedCurPosition != null) {
            curPosition = savedCurPosition.split(",");
        }
        return curPosition;
    }

    //封装请求参数
    private Map<String, String> requestFieldMap;

    public Map<String, String> getRequestFieldMap() {

        if (requestFieldMap == null) {
            requestFieldMap = new HashMap<>();
        }
        String uid = getUserId();
        if (uid != null) {
            requestFieldMap.put("userId", uid);
            requestFieldMap.put("token", getToken());
        } else {
            requestFieldMap.remove("userId");
            requestFieldMap.remove("token");
        }
        curPosition = getCurPosition();
        if (curPosition != null && null != curPosition[0]) {
            requestFieldMap.put("latitude", curPosition[0]);
            requestFieldMap.put("longitude", curPosition[1]);
        }
        requestFieldMap.put("timestamp", getTimestamp());
        requestFieldMap.put("sign", getSign());
        requestFieldMap.put("appVersion", getAppVersion());
        requestFieldMap.put("sdkVersion", getSdkVersion());
        //131北京  236 青岛
        requestFieldMap.put("areaCode", getAreaCode() + "");
        requestFieldMap.put("adCode", getAdCode() + "");
        requestFieldMap.put("platform", "1");
        return requestFieldMap;
    }

    private Map<String, String> requestHeaderMap;

    public Map<String, String> getRequestHeaderMap() {
        if (requestHeaderMap == null) {
            requestHeaderMap = new HashMap<>();
        }
        requestHeaderMap.put("x-incar-token", getHeaderToken());
        requestHeaderMap.put("x-operate-id", ApiStore.objectId);
        requestHeaderMap.put("x-incar-app-id", "3aaf0cefe92c4e8ba5cae892b798456c");
        curPosition = getCurPosition();
        if (curPosition != null && null != curPosition[0]) {
            requestHeaderMap.put("xlatitude", curPosition[0]);
            requestHeaderMap.put("xlongitude", curPosition[1]);
        }
        requestHeaderMap.put("x-incar-request-moudle", "staff");
        requestHeaderMap.put("x-incar-version", getAppVersion());
        requestHeaderMap.put("x-incar-timestamps", getTimestamp());
        if (BuildConfig.DEBUG) {
            requestHeaderMap.put("env", "debug");
        } else {
            requestHeaderMap.put("env", "release");
        }
        return requestHeaderMap;
    }

    private Map<String, String> webCookieMap;

    public Map<String, String> getCookieMap() {
        if (webCookieMap == null) {
            webCookieMap = new HashMap<>();
        }
        webCookieMap.putAll(getRequestFieldMap());
        webCookieMap.putAll(getRequestHeaderMap());
        webCookieMap.put("imgUrl", imageUrl);
        return webCookieMap;
    }
}